var saveFileDlg=function(config){
	this.doCancel = function(){
		this.close();
	};
	this.doSave = function(){
		var filename = this.textFileName.getValue();
		if (filename.indexOf('.') == -1){
			var extn = '';
			switch(config.panel.langCode){
				case 'javascript':
					extn = '.js';
					break;
				case 'text', 'generic':
					extn = '.txt';
					break;
				case 'css':
					extn = '.css';
					break;
				case 'html', 'htm':
					extn = '.html';
					break;
				case 'php':
					extn = '.php';
					break;
				case 'groovy' :
					extn = '.groovy';
					break;
				default:
					extn = '.txt';
					break;
			}
			filename += extn;
		}
		var filepath = this.stree.getSelectionModel().getSelectedNode().id + '/' + filename;
		Ext.Ajax.request({
            url:'fileexists.groovy',
            params:{
                file: filepath
            },
			method: 'GET',
            success: function (response, options){
				 var responseData = Ext.util.JSON.decode(response.responseText);
				 if (responseData.success){
				 	Ext.Msg.alert('Enregistrer','Fichier: ' + filepath + ' existe deja!<br/>Veuillez choisir un autre nom.', function(){
						this.textFileName.focus(true);
					}, this);
				 }
				 else{
				 	Ext.Ajax.request({
			            url:'save.groovy',
			            params:{
			                filename: filepath,
							contents: config.panel.code.getCode()
			            },
			            success: function (response, options){
							 var responseData = Ext.util.JSON.decode(response.responseText);
							 if (responseData.success){
							 	config.panel.newDocument=false;
								config.panel.urlCode = filepath;
								config.panel.title = filename;
								config.panel.setTitle(config.panel.title);
								Main.centerPanel.remove(config.panel, false);
								Ext.ComponentMgr.unregister(config.panel);
								var id = config.panel.getId();
								config.panel.id = filename;
								config.panel.el.id = filename;
								config.panel.el.set({id:filename});
								Ext.ComponentMgr.register(config.panel)
								Main.centerPanel.add(config.panel);
							 	config.panel.code.originalCode = config.panel.code.getCode();
								config.panel.propsGrid.setSource({
						        	"Nom": config.panel.title,
						        	"Chemin complet": config.panel.urlCode,
						        	"Type": responseData.fileinfo.filetype,
						        	"Derniere modification": responseData.fileinfo.lastmod,
						        	"Taille": responseData.fileinfo.size
						    	});
			                 	Ext.Msg.alert('Enregistrement','Fichier: ' + filepath + ' enregistré avec succes', function(){
									Main.sroot.reload();
									var path = this.stree.getSelectionModel().getSelectedNode().getPath();
									path += '|' + filepath;
									Main.stree.selectPath(path,null,function(bSuccess, oSelNode){
										if (bSuccess){
											config.panel.treeNode = oSelNode;
										}
									}.createDelegate(this));
									this.close();
								}, this);
							 }
							 else{
							 	Ext.Msg.alert('Erreur','Pas possible de sauvegarder le fichier: ' + filepath,  function(){
									this.close();
								}, this);
							 }
			            }.createDelegate(this),
			            failure: function(response, options){
			                Ext.Msg.alert('Erreur','Pas possible de sauvegarder le fichier: ' + filepath, function(){
								this.close();
							}, this);
					    }.createDelegate(this)
			        });
				 }
            }.createDelegate(this),
            failure: function(response, options){
                Ext.Msg.alert('Erreur','Pas possible de verifier le fichier: ' + filepath);
		    }.createDelegate(this)
        });
	};
	var saveButtonText ='Enregistrer';
	if (config.fileName){
		var saveButtonText ='Enregistrer sous';
	}
	this.saveButton = new Ext.Button({
		text: saveButtonText,
		handler: this.doSave,
		scope: this//,
	});
	this.cancelButton = new Ext.Button({
		text: 'Annuler',
		handler: this.doCancel,
		scope: this,
		disabled: false
	});
	this.stree = new Ext.tree.TreePanel({
		region: 'west',
		split:false,
		width:200,
		minSize:200,
		maxSize:200,
		titlebar:true,
		collapsible:true,
		showPin:false,
		cmargins:{
			top:0,
			left:0,
			right:0,
			bottom:0
		},
        animate:true,
        loader: new Ext.tree.TreeLoader({dataUrl:'list.groovy', clearOnLoad: true}),
        enableDrag:false,
        containerScroll: true,
		pathSeparator: '|'
    });
	this.stree.getLoader().requestMethod = 'GET';
    new Ext.tree.TreeSorter(this.stree, {folderSort:true});
    this.sroot = new Ext.tree.AsyncTreeNode({
        text: 'source',
        draggable:false,
        id:'source'
    });
    this.stree.setRootNode(this.sroot);
    this.sroot.expand(false, false);
	this.stree.on('click', function(node, e){
		this.fileStore.load({
			params: {node: node.id}
		});
	}.createDelegate(this))
	this.fileStore = new Ext.data.JsonStore({
		url: 'fileview.groovy',
		root: 'files',
		fields: ['filename', 'imgurl', 'qtip'],
		method: 'GET'
	});
	var tpl = new Ext.XTemplate(
		'<tpl for=".">',
            '<div class="thumb-wrap" qtip="{qtip}" qtitle="{filename}" id="view_{filename}">',
		    '<div class="thumb"><img src="{imgurl}" title="{filename}"></div>',
		    '<span>{shortName}</span></div>',
        '</tpl>',
        '<div class="x-clear"></div>'
	);
	this.view = new Ext.DataView({
		loadingText: 'Loading...',
		cls:'ychooser-view',
		region: 'center',
		singleSelect: true,
		store: this.fileStore,
		emptyText : '<div style="padding:10px;">No files to display</div>',
		tpl: tpl,
		itemSelector: 'div.thumb-wrap'
	});
	this.view.prepareData = function(data){
    	data.shortName = Ext.util.Format.ellipsis(data.filename, 15);
    	return data;
    };
	this.view.on('dblclick', function(view,index,node){
		this.textFileName.setValue(node.id.replace('view_',''));
		this.saveButton.enable();
	}, this);

	this.textFileName = new Ext.form.TextField({
		fieldLabel:'Filename',
		name:'fileName',
		allowBlank:false,
		invalidText:'Please enter a Filename!'
	});
	if (config.fileName){
		this.textFileName.setValue(config.fileName);
		this.saveButton.enable();
	}
	this.textFileName.on('change', function(){
		if (this.textFileName.isDirty()){
			this.saveButton.enable();
			this.saveButton.setText('Save As');
		}
	}.createDelegate(this));
	this.fileInput = new Ext.FormPanel({
		region: 'south',
		baseCls: 'x-plain',
		split:false,
		border: false,
		height:42,
		frame: true,
		minSize:42,
		maxSize:42,
		collapsible:false,
		animate:true,
		cmargins:{
			top:0,
			left:0,
			right:0,
			bottom:0
		},
		labelWidth: 75,
	    bodyStyle:'padding:10px;background:transparent url(images/default/window/top-bottom.png) repeat-x',
	    labelPad: 10,
	    defaultType: 'textfield',
	    defaults: {
	        // applied to each contained item
	        width: 230,
			height: 22,
	        msgTarget: 'side'
	    },
	    layoutConfig: {
	        // layout-specific configs go here
	        labelSeparator: ':'
	    },
	    items: this.textFileName
	});
	this.centerPanel = new Ext.Panel({
		region: 'center',
		baseCls: 'x-plain',
		layout:'border',
		border: false,
		bodyBorder: false,
		items: [
			this.view,
			this.fileInput
		]
	});
	this.saveDialog = new Ext.Window({
		id:'saveDialog',
		//baseCls: 'ychooser-dlg',
		modal: true,
		width:600,
		height:500,
		shadow:true,
		minWidth:600,
		minHeight:450,
		autoTabs:false,
		proxyDrag:false,
		collapsible:false,
		title: config.title,
		//bodyBorder: false,
		resizable: false,
		plain:true,
		keys: {
			key: 27,
			fn: this.doCancel,
			scope: this
		},
		layout: 'border',
		layoutConfig : {
			border: false,
			bodyBorder: false
		},
		buttons: [
			this.saveButton,
			this.cancelButton
		],
		items: [
			this.stree,
			this.centerPanel
		]
	});
};
saveFileDlg.prototype={
	show:function(config){
		this.saveDialog.show();
		this.saveButton.rendered = true;
		this.saveButton.disable();
		this.saveDialog.setTitle(config.title);
		if (config.fileName){
			this.textFileName.setValue(config.fileName)
			this.saveButton.enable();
		}
		else{
			this.textFileName.reset();
		}
		if(config.panel.treeNode){
			var path = config.panel.treeNode.parentNode.getPath();
			this.stree.selectPath(path,null,function(bSuccess, oSelNode){
				if (bSuccess){
					this.fileStore.load({
						params: {node: this.stree.getSelectionModel().getSelectedNode().id},
						callback: function(){
							this.view.select('view_' + config.fileName,false,true);
						}.createDelegate(this)
					});
				}
				else{
					this.stree.getSelectionModel().select(this.sroot);
					this.fileStore.load({
						params: {node: this.sroot.id},
						callback: function(){
							this.view.select('view_' + config.fileName,false,true);
						}.createDelegate(this)
					});
				}
			}.createDelegate(this));
		}
		else{
			this.stree.getSelectionModel().select(this.sroot);
			this.fileStore.load({
				params: {node: this.sroot.id}
			});
		}
	},
	close:function(){
		this.saveDialog.close();
	}
}
function saveFile(config){
	var dialogSave=new saveFileDlg(config);
	dialogSave.show(config);
};


FilePanel = function() {
	FilePanel.superclass.constructor.call(this, {
		region : 'west',
		el : 'west',
        title : 'Liste des fichiers',
        split : true,
        width : 200,
        minSize : 175,
        maxSize : 400,
        margins :'0 0 0 5',
		animate : true,
        autoScroll : true,
        loader: new Ext.tree.TreeLoader({dataUrl : 'list.groovy'}),
        enableDD:true,
        containerScroll : true,
		rootVisible : false,
        dropConfig : {appendOnly : true},
		root : new Ext.tree.AsyncTreeNode({
            text: 'chat',
            draggable:false, // disable root node dragging
            id:'source'
        })
	});
};

Ext.extend(FilePanel, Ext.tree.TreePanel, {
	selectFile : function(filePath) {
		this.selectPath(filePath);
	}
});

Ext.TemplateLayoutPanel = function(config){
	var menu = new Ext.menu.Menu({
		shadow: 'drop',
		minWidth: '100',
        items: [
            new Ext.menu.Item({
                text: 'Enregistrer',
				//icon: 'images/Save16.png',
                handler: function() {
					this.save();
				}.createDelegate(this)
            }),
			new Ext.menu.Item({
                text: 'Enregistrer sous...',
				//icon: 'images/SaveAs16.png',
                handler: function() {
					this.saveAs();
				}.createDelegate(this)
            })
        ]
    });
	this.tb = new Ext.Toolbar([
        {
            text : 'Fichier',
            //icon: 'images/Save16.png', // icons can also be specified inline
	        //cls: 'x-btn-icon',
        	tooltip: '<b>Enregistrer</b><br/>Enregistrer le fichier encours',
        	menu: menu
        },
        {
        	text : 'Enregistrer',
        	handler : function() {
        		this.save();
        	}.createDelegate(this)
        },
		{
			text : 'Proprietes',
            //icon: 'images/Table16.png', // icons can also be specified inline
	        //cls: 'x-btn-icon',
        	tooltip: '<b>Properties Fichier</b><br/>Properties du fichier encours',
			enableToggle: true,
			handler: function() {
				//this.propsGrid.expand();
				this.propsGrid.isVisible()?this.propsGrid.hide():this.propsGrid.show();
				this.doLayout();
				this.code.resize();
			}.createDelegate(this)
        },
		'-',
		{
			text : 'N de ligne',
			//icon: 'images/LineNumbers16.png', // icons can also be specified inline
	        //cls: 'x-btn-icon',
			enableToggle: true,
			pressed: true,
        	tooltip: '<b>Numero de ligne</b><br/>Aff/Cach le numero de ligne',
        	handler: function() {
				this.code.toggleLineNumbers();
			}.createDelegate(this)
		},
		'-', '->',
		{
			text : 'Tester',
			handler : function() {
				window.open('/gwc' + this.filePath);
			}.createDelegate(this)
		}
    ]);

	this.propsGrid = new Ext.grid.PropertyGrid({
        nameText: 'Proprietes',
		selModel: new Ext.grid.RowSelectionModel({singleSelect:true}),
        enableHdMenu: false,
        viewConfig : {
            forceFit:true,
            scrollOffset:2 // the grid will never have scrollbars
        },
		region: 'west',
		split:true,
		width:250,
		minSize:150,
		maxSize:350,
		titlebar:true,
		collapsible:false,
		animate:true,
		showPin:false,
		cmargins:{
			top:0,
			left:0,
			right:0,
			bottom:0
		},
		title:'Proprietes',
		alwaysShowTabs:false,
		hideTabs:false,
		preservePanels:false,
		collapsed:false,
		hidden: true
    });
	this.propsGrid.on('beforeedit', function(e){
		e.cancel = true;
	});
	this.filePath = config.filePath;
	this.title = config.title;
	this.langCode = config.langCode;
	this.treeNode = config.treeNode;
	if (this.filePath){
		this.newDocument = false;
		this.code = new Ext.ux.CodePress({
			region: 'center',
			deferredRender: false,
			titlebar:false,
			autoScroll:false,
			monitorResize: true,
			id: 'codepressSource'
			, language: this.langCode
			, autoResize: true
			, url: 'show.groovy?file=' + this.filePath
		});

		//var nodeQtip = this.treeNode.attributes.qtip.split('<br />');
		//var type = nodeQtip[0].split(': ')[1];
		//var lastModified = nodeQtip[1].split(': ')[1];
		//var size = nodeQtip[2].split(': ')[1];
		this.propsGrid.setSource({
        	"Nom": this.title,
        	"Chemin complet": this.filePath,
        	"Type": "groovy",
        	"Derniere modification": "12/01/2008",
        	"Taille": "30 kb"
    	});
	}
	else{
		this.newDocument = true;
		this.code = new Ext.ux.CodePress({
			region: 'center',
			deferredRender: false,
			titlebar:false,
			autoScroll:false,
			frame: true,
  		    monitorResize: true,
			id: 'codepressSource'
			, language: config.langCode
			, autoResize: true
			, code: ''
		});
		this.propsGrid.setSource({
        	"Nom": config.title,
        	"Chemin complet": '',
        	"Type": 'groovy',
        	"Derniere modification": new Date().format('M j, Y, g:i a'),
        	"Taille": '0 KB'
    	});
	}
	Ext.TemplateLayoutPanel.superclass.constructor.call(this, {
		id: config.title,
		deferredRender: false,
		closable: true,
		layout:'border',
		monitorResize: true,
		tbar: this.tb,
		items: [
			this.propsGrid,
			this.code
		]
	});
};
Ext.extend(Ext.TemplateLayoutPanel, Ext.Panel, {
	onResize: function(w,h){
		Ext.TemplateLayoutPanel.superclass.onResize.call(this, w, h);
		this.code.resize();
	},

	onRender : function(ct, position){
        Ext.TemplateLayoutPanel.superclass.onRender.call(this, ct, position);
	},

	afterRender : function(){
		Ext.TemplateLayoutPanel.superclass.afterRender.call(this);
		this.tb.setHeight(28);
		this.code.resize();
		//this.tb.addText('Font:');
    	//this.tb.addField(this.comboFontList);
	},
	isDirty : function(){
		return this.code.isDirty();
	},
	save : function(){
		if (this.newDocument){
			saveFile({panel: this, title: 'Enregistrer'});
		}
		else{
			if (this.isDirty()){
				Ext.Ajax.request({
		            url:'save.groovy',
		            params:{
		                filename: this.filePath,
						contents: this.code.getCode()
		            },
		            success: function (response, options){
						 var responseData = Ext.util.JSON.decode(response.responseText);
						 if (responseData.success){
						 	this.code.originalCode = this.code.getCode();
							this.propsGrid.setSource({
					        	"Nom": this.title,
					        	"Chemin complet": this.filePath,
					        	"Type": responseData.fileinfo.filetype,
					        	"Derniere modification": responseData.fileinfo.lastmod,
					        	"Taille": responseData.fileinfo.size
					    	});
		                 	Ext.Msg.alert('Enregistrement','Fichier: ' + this.title + ' enregistre avec succes', function(){
								var path = this.treeNode.getPath();
								var parentTree = this.treeNode.getOwnerTree();
								this.treeNode.parentNode.reload();
								parentTree.selectPath(path,null,function(bSuccess, oSelNode){
									if (bSuccess){
										this.treeNode = oSelNode;
									}
								}.createDelegate(this));
							}, this);
						 }
						 else{
						 	Ext.Msg.alert('Erreur','Pas possible de sauvegarder le fichier: ' + this.title);
						 }
		            }.createDelegate(this),
		            failure: function(response, options){
		                Ext.Msg.alert('Erreur','Pas possible de sauvegarder le fichier: ' + this.title);
				    }.createDelegate(this)
		        });
			}
		}
	},
	saveAs : function(){
		if (this.newDocument){
			saveFile({panel: this, title: 'Enregistrer'});
		}
		else{
			saveFile({panel: this, title: 'Enregistrer sous', fileName: this.title});
		}
	}
});

MainPanel = function(){

    MainPanel.superclass.constructor.call(this, {
        region:'center',
        margins:'0 5 5 0',
        resizeTabs: true,
        minTabWidth: 135,
        tabWidth: 135,
        enableTabScroll: true,
        activeTab: 0,

        items: {
            id:'welcome-panel',
            title: 'Home',
            html : 'Bienvenue au Groovy Web Chat Builder',
            iconCls:'icon-docs',
            autoScroll: true
        }
    });
};

Ext.extend(MainPanel, Ext.TabPanel, {
    loadFile : function(node){
        var tab = this.getComponent(node.text);
        if(tab){
            this.setActiveTab(tab);
        }else{
            var p = this.add(
            	new Ext.TemplateLayoutPanel(
            		{title:node.text, closable:true, autoScroll: false,
            		langCode: 'java', treeNode : node,
            		filePath : node.getPath().substring(7)})
            		//,
            		//urlCode : 'show.groovy?file=' + node.getPath().substring(7) /* length of /source */})
            );
            this.setActiveTab(p);
            p.on('bodyresize', function(){
				p.doLayout();
				p.code.resize();
			}, this);
        }
    }
});

Ext.onReady(function() {
	Ext.QuickTips.init();
	var filePanel = new FilePanel();
	var mainPanel = new MainPanel({id : 'center'});

	filePanel.on('click', function(node, e){
         if(node.isLeaf()){
            e.stopEvent();
            mainPanel.loadFile(node);
         }
    });

    mainPanel.on('tabchange', function(tp, tab) {
    	if (tab.file) {
        	filePanel.selectFile(tab.file);
    	}
    });

	var viewport = new Ext.Viewport({
		layout : 'border',
		items : [
			new Ext.BoxComponent({
				region : 'north',
				el : 'north',
				height : 50
			}), filePanel, mainPanel
		]
	});
});